package com.omronservice.web.webscoket;

import com.omronservice.web.webscoket.bean.BaseWebsocket;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 缓存机
 */
@ServerEndpoint("/GetBFFSParams/{line}/{index}")
@Component
public class BffsWebsocket extends BaseWebsocket {

    public static int onlineCount = 0;

    public final static List<BffsWebsocket> webSocketSet = new ArrayList<>();

    private Session session;

    @OnOpen
    public void onOpen (@PathParam(value="line") String line, @PathParam(value="index") String index, Session session){
        this.session = session;
        this.productionLine = line;
        this.productionNo = index;
        webSocketSet.add(this);
        addOnlineCount();
        System.out.println("BffsWebsocket有新链接加入!当前在线人数为" + getOnlineCount());
    }

    @OnClose
    public void onClose (){
        webSocketSet.remove(this);
        subOnlineCount();
        System.out.println("BffsWebsocket有一链接关闭!当前在线人数为" + getOnlineCount());
    }

    @OnMessage
    public void onMessage (String message, Session session) throws IOException {
        System.out.println("BffsWebsocket来自客户端的消息:" + message);
        // 群发消息
        for ( BffsWebsocket item : webSocketSet ){
            item.sendMessage(message+"223232");
        }
    }

    public void sendMessage (String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public static synchronized  int getOnlineCount (){
        return BffsWebsocket.onlineCount;
    }

    public static synchronized void addOnlineCount (){
        BffsWebsocket.onlineCount++;
    }

    public static synchronized void subOnlineCount (){
        BffsWebsocket.onlineCount--;
    }

}